大家好,我是Leo
今天要來講解,django object create的幾種方式
OK~~~ Let's go now!!!
假設我們今天有一張table,如下圖
models/init
from .doggle_model import *
models/doggle_model.py
from django.db import models
class doggle(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255,null=True,blank=True)
sex = models.IntegerField(null=True,blank=True)
age = models.IntegerField(null=True,blank=True)
created_at = models.DateTimeField(auto_now_add=True, editable=False)
updated_at = models.DateTimeField(auto_now_add=True, editable=False)
views/init
from .doggle import *
views/doggle
這種方式參數一多,就要寫很多欄位
from rest_framework.response import Response
from website.models import doggle
from rest_framework import permissions, views
class DoggleAPIView(views.APIView):
permission_classes = (permissions.AllowAny,)
authentication_classes = []
def post(self, request):
name = request.data.get('name',None)
age = request.data.get('age',None)
sex = request.data.get('sex',None)
doggle.objects.create(
name=name,
age=age,
sex=sex
)
return Response({"massage": True},status=201)
for 去跑參數,這邊如果request.data跟db model field name不一致時,要另行調整
透過dict的方式直接存入model內
from rest_framework.response import Response
from website.models import doggle
from rest_framework import permissions, views
class DoggleAPIView(views.APIView):
permission_classes = (permissions.AllowAny,)
authentication_classes = []
def post(self, request):
dic = dict()
for k,v in request.data.items():
dic[k] = v
doggle_model = doggle.objects.create(**dic)
doggle_model.save()
return Response({"massage": True},status=201)
第三種方式是將update and create寫在一起
pk=request.data.get('id') -> 這欄是判斷是否要新增或修改
也就是id出現在db內有出現則修改
也可以判斷多個 ex 在下面再帶個name = request.data.get('name')
from rest_framework.response import Response
from website.models import doggle
from rest_framework import permissions, views
class DoggleAPIView(views.APIView):
permission_classes = (permissions.AllowAny,)
authentication_classes = []
def post(self, request):
dic = dict()
for k,v in request.data.items():
dic[k] = v
obj, created = doggle.objects.update_or_create(
# check same name
pk=request.data.get('id'),
defaults=dic,
)
msg = 'create' if created else 'update'
return Response({"massage": True,"msg":msg},status=201)
from django.urls import path, include, re_path
from django.conf import settings
from django.conf.urls.static import static
from website.views import (
DoggleAPIView
)
urlpatterns = [
path('api/doggle/create',DoggleAPIView.as_view(),name='api-doggle-create'),
] +static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
今天主要是講解create的方式,明天我們來講method的方法
我們明天見,各位掰掰~~~